﻿using System;
using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Core.Base;
using Dolany.UtilityTool;
using Missbot.AIModule.OnlineStore;
using Missbot.Core.CrossingRoute;

namespace Missbot.AIModule.Vip
{
    public class DailyVipShopSvc : ISingleton, IViewable
    {
        public WaiterSvc WaiterSvc { get; set; }

        private List<IVipArmer> Armers { get; }

        public IVipArmer this[string Name] => Armers.FirstOrDefault(p => p.Name == Name);

        public DailyVipShopSvc()
        {
            Armers = AutofacSvc.LoadAllInstanceFromInterface<IVipArmer>();
        }

        public string[] RandGoods(int count)
        {
            return Rander.RandSort(Armers.ToArray())
                         .Take(count)
                         .Select(p => p.Name)
                         .ToArray();
        }

        public void Serve(InboxSession session, string serviceName)
        {
            var armer = Armers.FirstOrDefault(p => p.Name == serviceName);
            if (armer == null)
            {
                session.SendBack($"未找到相关内容：{serviceName}");
                return;
            }

            var osPerson = OSPersonDA.GetPerson(session.User.ID);
            if (osPerson.Diamonds < armer.DiamondsNeed)
            {
                session.SendBack($"钻石余额不足({osPerson.Diamonds.CurencyFormat("Diamond")}/{armer.DiamondsNeed.CurencyFormat("Diamond")})！");
                return;
            }

            if (!CheckLimit(session, armer))
            {
                return;
            }

            if (!CheckMaxContains(session, armer))
            {
                return;
            }

            if (!WaiterSvc.WaitForConfirm(session, $"此操作将花费{armer.DiamondsNeed.CurencyFormat("Diamond")}，是否继续？"))
            {
                session.SendBack("操作取消！");
                return;
            }

            if (!armer.Purchase(session))
            {
                return;
            }

            osPerson = OSPersonDA.GetPerson(session.User.ID);
            osPerson.Diamonds -= armer.DiamondsNeed;
            osPerson.Update();

            var purchaseRec = new VipSvcPurchaseRecord
            {
                UserID = session.User.ID,
                SvcName = armer.Name,
                PurchaseTime = DateTime.Now,
                Diamonds = armer.DiamondsNeed
            };
            purchaseRec.Insert();
        }

        private static bool CheckMaxContains(InboxSession session, IVipArmer armer)
        {
            if (armer.MaxContains == 0)
            {
                return true;
            }

            var armerRec = VipArmerDA.Get(session.User.ID);
            if (!armerRec?.CheckArmer(armer.Name, armer.MaxContains) ?? true)
            {
                return true;
            }

            session.SendBack($"你已经有{armer.MaxContains}件这个装备了！");
            return false;
        }

        private static bool CheckLimit(InboxSession session, IVipArmer armer)
        {
            if (armer.LimitCount == 0)
            {
                return true;
            }

            var (startDate, endDate) = ParseDateRange(armer.LimitInterval);
            var purchaseRec = VipSvcPurchaseDA.Get(session.User.ID, armer.Name, startDate, endDate);
            if (purchaseRec.Count < armer.LimitCount)
            {
                return true;
            }

            session.SendBack($"你{LimitIntervalToString(armer.LimitInterval)}已经买了{armer.LimitCount}次了");
            return false;
        }

        private static string LimitIntervalToString(VipArmerLimitInterval interval)
        {
            return interval switch
            {
                VipArmerLimitInterval.Daily => "今天",
                VipArmerLimitInterval.Weekly => "本周",
                VipArmerLimitInterval.Monthly => "本月",
                _ => default
            };
        }

        private static (DateTime, DateTime) ParseDateRange(VipArmerLimitInterval interval)
        {
            switch (interval)
            {
                case VipArmerLimitInterval.Daily:
                {
                    return (DateTime.Today, DateTime.Today.AddDays(1));
                }
                case VipArmerLimitInterval.Weekly:
                {
                    var startDate = DateTime.Now.DayOfWeek == DayOfWeek.Sunday
                                        ? DateTime.Today.AddDays(-6)
                                        : DateTime.Today.AddDays(1 - (int)DateTime.Now.DayOfWeek);
                    var endDate = startDate.AddDays(7);
                    return (startDate, endDate);
                }
                case VipArmerLimitInterval.Monthly:
                {
                    var startDate = DateTime.Today.AddDays(1 - DateTime.Now.Day);
                    var endDate = startDate.AddMonths(1);
                    return (startDate, endDate);
                }
                default:
                {
                    return default;
                }
            }
        }

        public (bool canView, string viewCommand) ViewableCheck(string name)
        {
            return this[name] == null ? (false, null) : (true, "查看装备");
        }
    }
}